package com.OtherExercises;

public class 数字加密 {
    public static void main(String[] args) {
        int originalPassword = 2023;
        System.out.println("原密码为:" + originalPassword);
        System.out.println("加密后为:" + encryptReturnInt(originalPassword));
        System.out.println("-------------------------");
        System.out.println("原密码为:" + originalPassword);
        System.out.println("加密后为:" + encryptReturnString(originalPassword));

    }

    /*
    原密码为:2023
    加密后为:8757
    -------------------------
    原密码为:2023
    加密后为:8757
    */

    //某系统的数字密码是一个四位数,如1983,为了安全,需要加密后再传输,加密规则是:对密码中的每一位数字,都加5,再对10求余,最后将所有数字顺序反转,得到一串加密后的新数,请设计出满足本需求的加密程序.

    public static int encryptReturnInt(int password) {
        int[] numbers = new int[4];//依次存放 个位,十位,百位.千位
        for (int i = 0, temp = password; i < numbers.length; i++) {
            numbers[i] = temp % 10;//依次存入各位数
            temp = temp / 10;
        }

        //+5%10
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] += 5;
            numbers[i] %= 10;
        }

        //numbers反转并计算出加密后的结果
        int sum = 0;
        for (int i = numbers.length - 1, weight = 1; i >= 0; i--) {//倒着遍历
            sum += numbers[i] * weight;//根据权重计算总和
            weight *= 10;//改变权重
        }
        return sum;
    }

    /**
     * 返回String版本的encryptReturnString
     *
     * @param password
     * @return String
     */
    public static String encryptReturnString(int password) {

        int[] numbers = split(password);//切分密码
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = (numbers[i] + 5) % 10;
        }

        reverseArr(numbers);//反转数组,或者也可以倒序遍历

        //把数组中的数拼接起来即可
        String result = "";
        for (int i = 0; i < numbers.length; i++) {
            result += numbers[i];
        }

        return result;
    }

    /**
     * 反转数组
     *
     * @param numbers
     */
    private static void reverseArr(int[] numbers) {
        for (int i = 0, temp; i < numbers.length / 2; i++) {
            temp = numbers[i];
            numbers[i] = numbers[numbers.length - 1 - i];
            numbers[numbers.length - 1 - i] = temp;
        }
    }

    /**
     * 将int型密码切分成int[]
     *
     * @param password
     * @return int[]
     */
    private static int[] split(int password) {
        int[] arr = new int[4];
        for (int i = arr.length - 1, temp = password; i >= 0; i--) {
            arr[i] = temp % 10;//倒序存入各位数
            temp = temp / 10;
        }
        return arr;
    }


}
